package bb.lanxing.activity.discover;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnButtonClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.team.LargeImageActivity;
import bb.lanxing.adapter.discover.BbsCommentAdapter;
import bb.lanxing.adapter.discover.BbsImageAdapter2;
import bb.lanxing.model.database.Bbs;
import bb.lanxing.model.database.User;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import okhttp3.Request;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BbsDetailActivity extends BaseActivity {
    private ImageView back;
    private ImageView deleteOrReport;

    private ImageView head;
    private TextView name;
    private TextView content;

    private RecyclerView imageGrid;
    private BbsImageAdapter2 bbsImageAdapter;
    private TextView time;
    private LinearLayout likeLayout;
    private ImageView likeIcon;
    private TextView like_number;

    private TextView commentNumber;

    private RecyclerView commentRecyclerView;
    private BbsCommentAdapter bbsCommentAdapter = new BbsCommentAdapter();

    private EditText commentInput;
    private TextView commentCommit;

    private ArrayList<String> largeImageList = new ArrayList<>();
    private ArrayList<Bbs> commentList = new ArrayList<>();

    private int bbsId;
    private int isLike;
    private int likesCount;

    private int userId;

    private int pageMax = 1;
    private int page = 1;
    private ProgressDialog progressDialog;

    private boolean isMine = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbs_detail);

        back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());
        deleteOrReport = findViewById(R.id.deleteOrReport);
        deleteOrReport.setOnClickListener(v -> showdeleteOrReportDialog());

        progressDialog = new ProgressDialog(this);
        NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView);
        nestedScrollView.setOnScrollChangeListener((View.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (!nestedScrollView.canScrollVertically(-1)) {
                loadData(true);
            } else if (!nestedScrollView.canScrollVertically(1)) {
                loadData(false);
            }
        });

        head = findViewById(R.id.head);

        name = findViewById(R.id.name);
        content = findViewById(R.id.content);
        imageGrid = findViewById(R.id.imageGrid);
        imageGrid.setLayoutManager(new GridLayoutManager(this, 3));
        bbsImageAdapter = new BbsImageAdapter2();
        bbsImageAdapter.setOnItemClickListener(position -> {
            Intent intent = new Intent(this, LargeImageActivity.class);
            intent.putStringArrayListExtra("images", largeImageList);
            intent.putExtra("currentImage", position);
            startActivity(intent);
        });
        imageGrid.setAdapter(bbsImageAdapter);
        time = findViewById(R.id.time);
        likeLayout = findViewById(R.id.bbs_like);
        likeLayout.setOnClickListener(v -> {
            if (0 == isLike) {
                isLike = 1;
                likesCount += 1;
            } else {
                isLike = 0;
                likesCount -= 1;
            }
            if (likesCount < 0) {
                likesCount = 0;
            }
            setlike(isLike);
            postlike(bbsId, isLike);
        });
        likeIcon = findViewById(R.id.likeIcon);
        like_number = findViewById(R.id.like_number);

        commentNumber = findViewById(R.id.commentNumber);

        commentRecyclerView = findViewById(R.id.commentList);
        commentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        bbsCommentAdapter.setOnItemClickListener(position -> commentDeal(position));
        bbsCommentAdapter.setLikeListener(position -> {
            if (0 == commentList.get(position).myLike) {
                commentList.get(position).myLike = 1;
                commentList.get(position).likesCount += 1;
            } else {
                commentList.get(position).myLike = 0;
                commentList.get(position).likesCount -= 1;
            }
            if (commentList.get(position).likesCount < 0) {
                commentList.get(position).likesCount = 0;
            }
            bbsCommentAdapter.notifyDataSetChanged();
            commitCommentlike(commentList.get(position).serverId, commentList.get(position).myLike);
        });
        commentRecyclerView.setAdapter(bbsCommentAdapter);

        commentInput = findViewById(R.id.commentInput);
        commentCommit = findViewById(R.id.commentCommit);
        commentCommit.setOnClickListener(v -> {
            postComment(commentInput.getText().toString());
            commentInput.setText("");
        });

        int bbsUserId = getIntent().getIntExtra("bbsUserId", 0);
        User signinUser = App.getContext().getSigninUser();
        if (signinUser != null) {
            userId = signinUser.getUid();
            if (userId != 0 && userId == bbsUserId) {
                isMine = true;
                deleteOrReport.setImageResource(R.drawable.delete);
            } else {
                deleteOrReport.setImageResource(R.drawable.report);
            }
        }
        String userHead = getIntent().getStringExtra("userHead");
        if (userHead != null) {
            Glide.with(this).load(userHead).transform(new RoundedCorners(30)).into(head);
        }
        name.setText(getIntent().getStringExtra("createBy"));
        content.setText(getIntent().getStringExtra("content"));
        ArrayList<String> imageList = getIntent().getStringArrayListExtra("imageList");
        largeImageList = getIntent().getStringArrayListExtra("largeImageList");
        if (imageList != null && !imageList.isEmpty()) {
            bbsImageAdapter.updateData(imageList);
        }

        time.setText(getIntent().getStringExtra("createTime"));
        likesCount = getIntent().getIntExtra("likesCount", 0);
        isLike = getIntent().getIntExtra("myLike", 0);
        setlike(isLike);
        commentNumber.setText(getIntent().getIntExtra("contentsCount", 0) + "");
        bbsId = getIntent().getIntExtra("id", 0);
        loadData(true);
    }

    private void setlike(int isLike) {
        if (isLike == 1) {
            likeIcon.setImageResource(R.drawable.liked);
            like_number.setTextColor(getColor(R.color.bbs_liked));
        } else {
            likeIcon.setImageResource(R.drawable.like);
            like_number.setTextColor(getColor(R.color.bbs_like));
        }
        like_number.setText(likesCount + "");
    }

    private void loadData(final boolean bPullDown) {
        if (bPullDown) {
            page = 1;
        } else {
            page++;
            if (page > pageMax) {
                return;
            }
        }
        progressDialog.show();
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
                progressDialog.dismiss();
            }

            @Override
            public void onResponseString(@NonNull String string) {
                progressDialog.dismiss();
                if (!TextUtils.isEmpty(string)) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        int code = jsonObject.optInt("code");
                        if (200 == code) {
                            int totalListNumber = jsonObject.optInt("total");
                            pageMax = totalListNumber / 10;
                            if (totalListNumber % 10 > 0) {
                                pageMax++;
                            }
                            ArrayList<Bbs> arrayList = new ArrayList<>();
                            try {
                                JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                                for (int i = 0; i < jSONArray.length(); i++) {
                                    Bbs createByJson = Bbs.createByJson(jSONArray.getJSONObject(i));
                                    arrayList.add(createByJson);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            updateDatas(arrayList, bPullDown);
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    toast(getString(R.string.failed_get_review));
                }
            }
        };
        MyHttpClient.requestBbsCommentList(biCiCallback, bbsId, page, 10, userId);
    }

    private synchronized void updateDatas(final List<Bbs> arrayList, final boolean needClean) {
        if (arrayList == null) {
            return;
        }
        runOnUiThread(() -> {
            if (bbsCommentAdapter != null) {
                if (needClean) {
                    commentList.clear();
                }
                commentList.addAll(arrayList);
                commentNumber.setText(commentList.size() + "");
                bbsCommentAdapter.updateData(commentList);
            }
        });
    }

    private void showdeleteOrReportDialog() {
        if (isMine) {
            new CircleDialog.Builder().setTitle(getString(R.string.delete)).setText(getString(R.string.deleted_posts_not_be_restored))
                    .setPositive(getString(R.string.confirm), v -> {
                        deleteBbs();
                        return true;
                    }).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                    .show(getSupportFragmentManager());
        } else {
            new CircleDialog.Builder().setTitle(getString(R.string.report_a_post)).setText(getString(R.string.report_a_post_content))
                    .setPositive(getString(R.string.confirm), v -> {
                        Intent intent = new Intent(this, BbsReportActivity.class);
                        intent.putExtra("content", getIntent().getStringExtra("content"));
                        intent.putExtra("blogId", bbsId);
                        startActivity(intent);
                        return true;
                    }).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                    .show(getSupportFragmentManager());
        }
    }

    private void deleteBbs() {
        showLoadingDialog(getString(R.string.deleting_post), true, null);
        Observable.create(new NetSubscribe(MyHttpClient.deleteBbs(bbsId))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.failed_delete_post));
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    toast(getString(R.string.successed_delete_post));
                                    finish();
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.failed_delete_post));
                        }
                    }
                });
    }

    private void postlike(int bbsId, int isLike) {
        Observable.create(new NetSubscribe(MyHttpClient.commitBbslike(bbsId, isLike))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.fail_like));
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.fail_like));
                        }
                    }
                });
    }

    private void commitCommentlike(int bbsId, int isLike) {
        Observable.create(new NetSubscribe(MyHttpClient.commitCommentlike(bbsId, isLike))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.fail_like));
                    }

                    @Override
                    public void onNext(String str) {
                        System.out.println("commitCommentlike: " + str);
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.fail_like));
                        }
                    }
                });
    }

    private void deleteComment(int commentId) {
        System.out.println("deleteComment222: " + commentId);
        showLoadingDialog(getString(R.string.deleting_comment), true, null);
        Observable.create(new NetSubscribe(MyHttpClient.deleteComment(commentId))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.failed_delete_comment));
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        System.out.println("deleteComment: " + str);
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    toast(getString(R.string.successed_delete_comment));
                                    loadData(true);
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.failed_delete_comment));
                        }
                    }
                });
    }

    private void postComment(String commentText) {
        if (TextUtils.isEmpty(commentText)) {
            App.getContext().showMessage(getString(R.string.text_not_be_empty));
            return;
        }
        showLoadingDialog(getString(R.string.posting_review), true, null);
        Observable.create(new NetSubscribe(MyHttpClient.createBbsComment(bbsId, commentText))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.failed_post_review));
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    toast(getString(R.string.successed_post_review));
                                    loadData(true);
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.failed_post_review));
                        }
                    }
                });
    }

    private void commentDeal(int position) {
        if (userId != 0) {
            if (userId == commentList.get(position).userId) {
                new CircleDialog.Builder().setTitle(getString(R.string.delete)).setText(getString(R.string.deleted_comments_not_be_restored))
                        .setPositive(getString(R.string.confirm), v -> {
                            deleteComment(commentList.get(position).serverId);
                            return true;
                        }).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                        .show(getSupportFragmentManager());
            } else {
                new CircleDialog.Builder().setItems(new String[]{getString(R.string.reply_to_review), getString(R.string.report_comment)}, (parent, view1, position1, id) -> {
                                    if (position1 == 0) {
                                        replyComment(position);
                                    } else {
                                        Intent intent = new Intent(this, BbsReportActivity.class);
                                        intent.putExtra("content", commentList.get(position).content);
                                        intent.putExtra("commentId", commentList.get(position).serverId);
                                        startActivity(intent);
                                    }
                                    return true;
                                }
                        ).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                        .show(getSupportFragmentManager());
            }
        }
    }

    private void replyComment(int position) {
        new CircleDialog.Builder().setTitle(getString(R.string.leave_comment)).setInputCounter(140)
                .setInputHint(getString(R.string.leave_comment_hint) + commentList.get(position).createBy)
                .setPositiveInput(getString(R.string.confirm), (text, editText) -> {
                    if (!TextUtils.isEmpty(text)) {
                        postComment(getString(R.string.post_reply) + commentList.get(position).createBy + ": " + text);
                        return true;
                    } else {
                        return false;
                    }
                }).setNegative(getString(R.string.cancel), (OnButtonClickListener) null)
                .show(getSupportFragmentManager());
    }
}